using MySql.Data.MySqlClient;
using System.Data;

namespace Tools.Android
{
    public partial class AndroidMain : Form
    {
        private List<ConnectionInfo> _connections;
        private ConnectionInfo _currentConnection;
        private string _connStr = "";
        private string _tableName = "";
        private List<string> _tableNameList = null;

        private DataTable _dataTable;
        public AndroidMain()
        {
            InitializeComponent();
            _connections = new List<ConnectionInfo>();
            _currentConnection = new ConnectionInfo();
            _tableNameList = new List<string>();
        }

        private void mySqlToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MySqlConnectForm _form = new MySqlConnectForm();
            _form.ShowDialog();
        }

        private void sqlite连接ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SqliteConnectForm _form = new SqliteConnectForm();
            _form.ShowDialog();
        }




        // 加载保存的连接
        private void LoadSavedConnections()
        {
            try
            {
                _connections = ConfigHelper.LoadConnections();
                //lst_connections.Items.Clear();
                foreach (var conn in _connections)
                {
                    //lst_connections.Items.Add(conn.ConnectionName);
                    treeView1.Nodes.Add(conn.ConnectionName);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载连接失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                _connections = new List<ConnectionInfo>();
            }
        }

        private void 刷新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LoadSavedConnections();
        }



        private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            // 获取当前双击的节点
            TreeNode selectedNode = e.Node;


            if (e.Node.Level == 0 && e.Node.Nodes.Count == 0)
            {
                _currentConnection = ConfigHelper.LoadConnections().Where(x => x.ConnectionName == selectedNode.Text).FirstOrDefault();

                _connStr = _currentConnection.GetConnectionString();
                using (var conn = new MySqlConnection(_currentConnection.GetConnectionString()))
                {
                    try
                    {
                        conn.Open();

                        // 方法1：使用 SHOW TABLES
                        using (var cmd = new MySqlCommand("SHOW TABLES", conn))
                        using (var reader = cmd.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                //lstTables.Items.Add(reader.GetString(0));
                                treeView1.SelectedNode.Nodes.Add(reader.GetString(0));

                                _tableNameList.Add(reader.GetString(0));
                                treeView1.ExpandAll();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"加载表失败: {ex.Message}");
                    }
                }
            }
            if (e.Node.Level == 1)
            {
                // 获取表结构
                var schema = GetTableSchema(e.Node.Text);
                _tableName = e.Node.Text;

                // 显示在右侧面板中
                dataGridView1.DataSource = schema;

                _dataTable = schema;
            }

        }



        //获取表结构方法 - 核心实现
        public DataTable GetTableSchema(string tableName)
        {
            try
            {
                using (MySqlConnection conn = new MySqlConnection(_connStr))
                {
                    conn.Open();

                    string detailedSql = $@"
                        SELECT 
                            COLUMN_NAME AS '字段名',
                            COLUMN_TYPE AS '类型',
                            IS_NULLABLE AS '允许空',
                            COLUMN_KEY AS '键类型',
                            COLUMN_COMMENT AS '字段描述'
                        FROM INFORMATION_SCHEMA.COLUMNS 
                        WHERE TABLE_SCHEMA = '{conn.Database}' 
                        AND TABLE_NAME = '{tableName}'";


                    using (MySqlCommand cmd = new MySqlCommand(detailedSql, conn))
                    {
                        DataTable schema = new DataTable();
                        MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
                        adapter.Fill(schema);
                        return schema;
                    }
                }
            }
            catch (Exception ex)
            {
                //statusLabel.Text = $"获取表结构失败: {ex.Message}";
                return new DataTable(); // 返回空表
            }
        }

        private void 生成代码ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var _path = Path.GetDirectoryName(Application.ExecutablePath) + "\\android\\";
            FileFolderHelper.CreateFileDirectory(_path);
            string javaCode = new EntityConverter().ConvertToJavaEntity(_currentConnection.GetConnectionString(), _tableName, _currentConnection.Database);

            File.WriteAllText($"{_path}{_tableName}.java", javaCode);
            MessageBox.Show("生成完成！");
        }

        private void 遍历所有表ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var _path = Path.GetDirectoryName(Application.ExecutablePath) + "\\android\\";
            FileFolderHelper.CreateFileDirectory(_path);
            foreach (var item in _tableNameList)
            {
                string javaCode = new EntityConverter().ConvertToJavaEntity(_currentConnection.GetConnectionString(), item, _currentConnection.Database);

                File.WriteAllText($"{_path}{item}.java", javaCode);

            }
            MessageBox.Show("生成完成！");
        }

        private void vS代码生成ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var _path = Path.GetDirectoryName(Application.ExecutablePath) + "\\vsCode\\";
            FileFolderHelper.CreateFileDirectory(_path);

            var vsCode = new VSCodeEntityConverter().ConvertToVSCodeEntitys(_currentConnection.GetConnectionString(), _tableName, _currentConnection.Database);

            File.WriteAllText($"{_path}{_tableName}.ts", vsCode);
            File.WriteAllText($"{_path}add-{_tableName}.ts", vsCode);
            File.WriteAllText($"{_path}update-{_tableName}.ts", vsCode);
            File.WriteAllText($"{_path}delete-{_tableName}.ts", vsCode);
            File.WriteAllText($"{_path}page-{_tableName}.ts", vsCode);
            File.WriteAllText($"{_path}admin-result-sql-sugar-paged-list-{_tableName}.ts", vsCode);
            File.WriteAllText($"{_path}admin-result-{_tableName}.ts", vsCode);
            File.WriteAllText($"{_path}admin-result-list-{_tableName}.ts", vsCode);
            File.WriteAllText($"{_path}sql-sugar-paged-list-{_tableName}.ts", vsCode);
            MessageBox.Show("生成完成！");
        }

        private void api及model生成ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Api及Model生成 _form = new Api及Model生成(_dataTable);
            _form.Show();
        }

    }





}
